<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>配置编辑器</title>
    <script src="https://unpkg.com/@tailwindcss/browser@4"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style type="text/tailwindcss">
        @theme {
            --color-primary: #4F46E5;
            --color-secondary: #10B981;
            --color-accent: #F59E0B;
            --color-dark: #1F2937;
            --color-light: #F9FAFB;
            --font-inter: 'Inter', sans-serif;
        }

        @utility smooth-transition {
            transition: all 0.3s ease-in-out;
        }

        @utility card-shadow {
            box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
        }

        @utility hover-scale {
            transform: scale(1.02);
        }

        /* 弹窗动画 */
        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: scale(0.9);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }

        .modal-container {
            animation: modalFadeIn 0.3s ease-out;
        }

        /* 半透明背景 */
        .modal-backdrop {
            background-color: rgba(0, 0, 0, 0.3);
        }

        body {
            font-family: var(--font-inter), system-ui, sans-serif;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-5xl">
        <!-- 页面标题 -->
        <header class="text-center mb-12">
            <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-dark mb-2">部落冲突打鱼辅助</h1>
            <p class="text-gray-500 text-lg">解放双手，资源不断</p>
        </header>

        <!-- 配置卡片区 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
            <!-- 用户输入卡片 -->
            <div class="bg-white rounded-xl p-6 card-shadow smooth-transition hover:hover-scale col-span-1">
                <div class="flex items-center mb-4">
                    <i class="fas fa-user-circle text-primary text-2xl mr-3"></i>
                    <h2 class="text-xl font-semibold text-dark">用户密钥</h2>
                </div>
                <div class="space-y-4">
                    <input type="text" id="userKey" class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-primary focus:border-primary smooth-transition"
                        placeholder="用户密钥">
                    <div id="userValidation" class="text-sm text-red-500 hidden"></div>
                </div>
            </div>

            <!-- 配置组选择卡片 -->
            <div class="bg-white rounded-xl p-6 card-shadow smooth-transition hover:hover-scale col-span-2">
                <div class="flex items-center mb-4">
                    <i class="fas fa-layer-group text-secondary text-2xl mr-3"></i>
                    <h2 class="text-xl font-semibold text-dark">配置组</h2>
                </div>
                <div class="space-y-4">
                    <!-- 配置组列表 -->
                    <div id="configGroupContainer" class="hidden">
                        <div id="configGroupList" class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <!-- 配置组项将通过JavaScript动态生成 -->
                        </div>
                    </div>
                    <div id="configGroupPlaceholder" class="text-gray-500 text-center py-4">
                        请先输入用户密钥
                    </div>
                </div>
            </div>
        </div>

        <!-- 配置组弹窗 -->
        <div id="groupConfigModal" class="fixed inset-0 modal-backdrop hidden items-center justify-center z-50 opacity-0 pointer-events-none transition-opacity duration-300">
            <div class="modal-container bg-white rounded-xl p-6 card-shadow max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto transform scale-95 transition-transform duration-300">
                <div class="flex justify-between items-center mb-4">
                    <h3 id="modalGroupTitle" class="text-xl font-semibold text-dark">配置组</h3>
                    <button id="closeGroupModal" class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="mb-6">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">配置项</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">当前值</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">新值</th>
                            </tr>
                        </thead>
                        <tbody id="groupConfigTableBody" class="bg-white divide-y divide-gray-200">
                            <!-- 表格行将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>
                <div class="flex justify-end space-x-3">
                    <button id="cancelGroupModal" class="px-4 py-2 bg-gray-200 text-gray-700 font-medium rounded-lg hover:bg-gray-300 smooth-transition">
                        取消
                    </button>
                    <button id="saveGroupModal" class="px-4 py-2 bg-primary text-white font-medium rounded-lg hover:bg-primary/90 smooth-transition">
                        保存
                    </button>
                </div>
            </div>
        </div>

        <!-- 操作结果提示 -->
        <div id="resultMessage" class="hidden fixed bottom-6 right-6 px-6 py-3 rounded-lg shadow-lg transform translate-y-4 opacity-0 smooth-transition max-w-md"></div>
    </div>

    <script>
        // 存储配置数据
        let configData = {};
        // 存储当前正在编辑的配置组
        let currentEditGroup = '';

        // 配置组和配置项的别名映射
        const aliasMap = {
            "openai": {"name": "豆包AI配置"},
            "baidu_ocr": {"name": "百度OCR配置"},
            "bing": {"name": "主世界兵种数量"},
            "ybing": {"name": "夜世界兵种数量"},
            "base_url": {"name": "API基础URL"},
            "api_key": {"name": "API密钥"},
            "client_id": {"name": "客户端ID"},
            "client_secret": {"name": "客户端密钥"},
            "token_url": {"name": "令牌URL"},
            "one": {"name": "第一格"},
            "two": {"name": "第二格"},
            "three": {"name": "第三格"},
            "four": {"name": "第四格"},
            "five": {"name": "第五格"},
            "six": {"name": "第六格"},
            "seven": {"name": "第七格"},
            "eight": {"name": "第八格"},
            "nine": {"name": "第九格"},
            "ten": {"name": "第十格"},
            "eleven": {"name": "第十一格"},
            "yone": {"name": "夜世界第一格"},
            "ytwo": {"name": "夜世界第二格"},
            "ythree": {"name": "夜世界第三格"},
            "yfour": {"name": "夜世界第四格"},
            "yfive": {"name": "夜世界第五格"},
            "ysix": {"name": "夜世界第六格"},
            "yseven": {"name": "夜世界第七格"},
            "yeight": {"name": "夜世界第八格"},
            "ynine": {"name": "夜世界第九格"},
            "yten": {"name": "夜世界第十格"},
            "yeleven": {"name": "夜世界第十一格"},
          
            "ziyuan": {"name": "资源阈值(达到这个阈值才会开始下兵)"},
            "moshi": {"name": "搜鱼模式"},
            "home": {"name": "修改(0:家乡,1:夜世界)"},
            "0": {"name": "家乡"},
            "1": {"name": "夜世界"},
            "phone_configs" : {"name": "手机配置"},
            "console" : {"name": "控制台窗口显示位置与大小"},
            "game_end_button": {"name": "游戏结束按钮坐标"},
            "resources": {"name": "资源截图区域"},
            "game_end": {"name": "游戏结束检测区域"},
            "abnormal": {"name": "异常检测区域"},
            "fishing_start_1": {"name": "空白区域(防止弹窗)"},
            "fishing_start_2": {"name": "空白区域(防止弹窗)"},
            "fishing_start_3": {"name": "进攻按钮"},
            "fishing_start_4": {"name": "搜索按钮"},
            "yfishing_start_1": {"name": "夜世界空白区域(防止弹窗)"},
            "yfishing_start_2": {"name": "夜世界空白区域(防止弹窗)"},
            "yfishing_start_3": {"name": "夜世界进攻按钮"},
            "yfishing_start_4": {"name": "夜世界搜索按钮"},
            "return_base": {"name": "回营位置"},
            "peibing": {"name": "主世界下兵配置"},
            "ypeibing": {"name": "夜世界下兵配置"},
            "troopSlotsOccupied": {"name": "兵种占了几个格子"},
            "troopSlotWithHeroSkill": {"name": "那几个格子英雄有技能"},
            "troopSlotToSwipe": {"name": "哪个格子需要一字划"},
            "jixu": {"name": "继续搜索"},
  


      
        };

        // DOM元素
        const userKeyInput = document.getElementById('userKey');
        const userValidation = document.getElementById('userValidation');
        // 配置组相关元素
        const configGroupContainer = document.getElementById('configGroupContainer');
        const configGroupList = document.getElementById('configGroupList');
        const configGroupPlaceholder = document.getElementById('configGroupPlaceholder');
        // 配置组弹窗相关元素
        const groupConfigModal = document.getElementById('groupConfigModal');
        const modalGroupTitle = document.getElementById('modalGroupTitle');
        const groupConfigTableBody = document.getElementById('groupConfigTableBody');
        const closeGroupModal = document.getElementById('closeGroupModal');
        const cancelGroupModal = document.getElementById('cancelGroupModal');
        const saveGroupModal = document.getElementById('saveGroupModal');
        const resultMessage = document.getElementById('resultMessage');

        // 通过API获取用户配置的函数
        async function fetchUserConfig(userKey) {
            try {
                showMessage('正在获取配置...', 'info');
                const response = await fetch('/config', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'text/plain',
                    },
                    body: userKey
                });
                if (!response.ok) {
                    throw new Error(`用户不存在`);
                }
                const data = await response.json();
                configData = data.user_config;
                showMessage('配置获取成功', 'success');
                // 使用JSON.stringify完整显示配置信息
                console.log('配置获取成功:', JSON.stringify(configData, null, 2));
                return configData;
            } catch (error) {
                console.error('获取用户配置失败:', error);
                showMessage(`获取配置失败: ${error.message}`, 'error');
                return null;
            }
        }

        // 用户输入变化事件
        userKeyInput.addEventListener('input', async () => {
            const inputUser = userKeyInput.value.trim();

            // 清空并隐藏配置组列表
            configGroupList.innerHTML = '';
            configGroupContainer.classList.add('hidden');
            configGroupPlaceholder.classList.remove('hidden');
            configGroupPlaceholder.textContent = '请先输入用户密钥';
            
            userValidation.classList.add('hidden');

            // 如果输入了用户ID，尝试获取配置
            if (inputUser) {
                const config = await fetchUserConfig(inputUser);
                if (config) {
                    // 显示配置组列表
                    configGroupPlaceholder.classList.add('hidden');
                    configGroupContainer.classList.remove('hidden');
                    
                    // 填充配置组列表
                    populateConfigGroupList(config);
                } else {
                    // 用户配置不存在时显示错误
                    userValidation.textContent = '该用户ID不存在或获取配置失败';
                    userValidation.classList.remove('hidden');
                }
            }
        });

        // 填充配置组列表
        function populateConfigGroupList(config) {
            configGroupList.innerHTML = '';
            
            // 为每个配置组创建一个卡片
            Object.keys(config).forEach(group => {
                const groupName = aliasMap[group]?.name || group;
                
                const groupCard = document.createElement('div');
                groupCard.className = 'bg-gray-50 rounded-lg p-4 cursor-pointer hover:bg-gray-100 smooth-transition border border-gray-200';
                groupCard.dataset.group = group;
                
                groupCard.innerHTML = `
                    <div class="flex items-center">
                        <i class="fas fa-folder text-secondary mr-2"></i>
                        <span class="font-medium text-gray-900">${groupName}</span>
                    </div>
                    <div class="mt-2 text-sm text-gray-500">
                        ${Object.keys(config[group]).length} 个配置项
                    </div>
                `;
                
                groupCard.addEventListener('click', () => openGroupConfigModal(group, groupName, config[group]));
                configGroupList.appendChild(groupCard);
            });
        }

        // 格式化配置值显示
        function formatConfigValue(value) {
            if (typeof value === 'object' && value !== null) {
                // 如果是对象，转换为格式化的JSON字符串显示
                return JSON.stringify(value, null, 2);
            }
            return value;
        }

        // 打开配置组弹窗
        function openGroupConfigModal(group, groupName, groupConfig) {
            currentEditGroup = group;
            
            // 设置弹窗标题
            modalGroupTitle.textContent = groupName;
            
            // 填充配置项表格
            groupConfigTableBody.innerHTML = '';
            
            Object.keys(groupConfig).forEach(key => {
                const keyValue = groupConfig[key];
                const keyName = aliasMap[key]?.name || key;
                
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50';
                row.dataset.key = key;
                
                // 特殊处理phone_configs组
                if (group === 'phone_configs') {
                    // 对于phone_configs，每个子项都是一个手机配置对象
                    const phoneConfig = keyValue;
                    let phoneConfigHtml = '';
                    
                    // 为手机配置中的每个字段创建输入框
                    Object.keys(phoneConfig).forEach(fieldKey => {
                        const fieldValue = phoneConfig[fieldKey];
                        const fieldName = aliasMap[fieldKey]?.name || fieldKey;
                        
                        if (typeof fieldValue === 'object' && fieldValue !== null) {
                            // 对于对象类型的字段（如console），创建多个输入框
                            phoneConfigHtml += `
                                <div class="mb-3 p-3 bg-gray-50 rounded">
                                    <h4 class="font-medium text-gray-700 mb-2">${fieldName}</h4>
                                    <div class="grid grid-cols-2 gap-2">
                                        ${Object.keys(fieldValue).map(subKey => `
                                            <div>
                                                <label class="block text-xs text-gray-500">${subKey}</label>
                                                <input type="number" 
                                                       data-field="${fieldKey}" 
                                                       data-subfield="${subKey}"
                                                       value="${fieldValue[subKey]}" 
                                                       class="w-full px-2 py-1 text-sm border border-gray-300 rounded focus:ring-1 focus:ring-primary">
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            `;
                        } else {
                            // 对于简单类型的字段
                            phoneConfigHtml += `
                                <div class="mb-2">
                                    <label class="block text-sm font-medium text-gray-700">${fieldName}</label>
                                    <input type="text" 
                                           value="${fieldValue}" 
                                           data-field="${fieldKey}"
                                           class="w-full px-3 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-primary">
                                </div>
                            `;
                        }
                    });
                    
                    row.innerHTML = `
                        <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900">${keyName}</td>
                        <td class="px-4 py-3 text-sm text-gray-500" colspan="2">
                            <div class="space-y-2">
                                ${phoneConfigHtml}
                                <div class="pt-2">
                                    <button class="px-3 py-1 bg-primary text-white text-sm rounded hover:bg-primary/90"
                                            onclick="savePhoneConfig('${key}')">
                                        保存 ${keyName}
                                    </button>
                                </div>
                            </div>
                        </td>
                    `;
                } else {
                    // 其他配置组的处理方式保持不变
                    const isObject = typeof keyValue === 'object' && keyValue !== null;
                    const formattedValue = formatConfigValue(keyValue);
                    
                    row.innerHTML = `
                        <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900">${keyName}</td>
                        <td class="px-4 py-3 text-sm text-gray-500 whitespace-pre-wrap">${formattedValue}</td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                            <textarea 
                                class="w-full px-3 py-1 border border-gray-300 rounded-md focus:ring-2 focus:ring-primary focus:border-primary"
                                rows="4"
                                data-original-value="${formattedValue.replace(/"/g, '&quot;')}">${formattedValue}</textarea>
                        </td>
                    `;
                }
                
                groupConfigTableBody.appendChild(row);
            });
            
            // 显示弹窗动画
            groupConfigModal.classList.remove('hidden', 'opacity-0', 'pointer-events-none');
            groupConfigModal.classList.add('flex');
            
            // 触发动画
            setTimeout(() => {
                groupConfigModal.classList.remove('opacity-0');
                const modalContainer = groupConfigModal.querySelector('.modal-container');
                modalContainer.classList.remove('scale-95');
            }, 10);
        }

        // 关闭配置组弹窗
        function closeGroupConfigModal() {
            // 添加关闭动画
            groupConfigModal.classList.add('opacity-0');
            const modalContainer = groupConfigModal.querySelector('.modal-container');
            modalContainer.classList.add('scale-95');
            
            // 动画结束后隐藏元素
            setTimeout(() => {
                groupConfigModal.classList.add('hidden', 'pointer-events-none');
                groupConfigModal.classList.remove('flex');
            }, 300);
        }

        // 保存手机配置
        async function savePhoneConfig(phoneKey) {
            const inputUser = userKeyInput.value.trim();
            
            if (!inputUser) {
                showMessage('请先输入用户密钥', 'error');
                return;
            }
            
            // 获取该手机的所有配置输入框
            const phoneContainer = document.querySelector(`tr[data-key="${phoneKey}"]`);
            const phoneInputs = phoneContainer.querySelectorAll('input[data-field]');
            const phoneConfig = {};
            
            // 收集所有配置值
            phoneInputs.forEach(input => {
                const field = input.dataset.field;
                const subfield = input.dataset.subfield;
                
                if (subfield) {
                    // 对于有子字段的对象类型配置
                    if (!phoneConfig[field]) {
                        phoneConfig[field] = {};
                    }
                    // 对于数字类型的字段，保存为数字
                    const value = input.type === 'number' ? parseFloat(input.value) || 0 : input.value;
                    phoneConfig[field][subfield] = value;
                } else {
                    // 对于简单类型的配置
                    phoneConfig[field] = input.value;
                }
            });
            
            try {
                // 发送更新请求
                const encodedNewValue = encodeURIComponent(JSON.stringify(phoneConfig));
                
                const response = await fetch(`/config/update/?user_key=${inputUser}&config_group=phone_configs&config_key=${phoneKey}&new_value=${encodedNewValue}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                });
                
                const data = await response.json();
                
                if (response.ok && data.status === 'success') {
                    showMessage(`手机配置 ${phoneKey} 更新成功`, 'success');
                    // 更新主配置数据
                    if (configData.phone_configs) {
                        configData.phone_configs[phoneKey] = phoneConfig;
                    }
                } else {
                    showMessage(`更新失败: ${data.message || '未知错误'}`, 'error');
                }
            } catch (error) {
                console.error('更新配置时发生网络错误:', error);
                showMessage('网络错误：' + error.message, 'error');
            }
        }

        // 保存配置组修改
        async function saveGroupConfig() {
            const inputUser = userKeyInput.value.trim();
            
            if (!inputUser) {
                showMessage('请先输入用户密钥', 'error');
                return;
            }
            
            // 收集所有修改过的配置
            const modifiedConfigs = [];
            const rows = groupConfigTableBody.querySelectorAll('tr');
            
            rows.forEach(row => {
                const key = row.dataset.key;
                const textarea = row.querySelector('textarea');
                
                // 如果没有textarea元素（可能是phone_configs），跳过
                if (!textarea) return;
                
                // 获取textarea中的值
                const newValue = textarea.value.trim();
                const originalValue = textarea.dataset.originalValue;
                
                // 只收集有修改的配置
                if (newValue !== originalValue) {
                    modifiedConfigs.push({
                        key: key,
                        newValue: newValue,
                        originalValue: originalValue
                    });
                }
            });

            if (modifiedConfigs.length === 0) {
                // 没有修改，直接关闭弹窗
                closeGroupConfigModal();
                return;
            }

            try {
                showMessage(`正在更新${modifiedConfigs.length}个配置...`, 'info');
                
                // 逐个更新配置
                let successCount = 0;
                let failCount = 0;
                
                for (const config of modifiedConfigs) {
                    try {
                        const encodedNewValue = encodeURIComponent(config.newValue);
                        const response = await fetch(`/config/update/?user_key=${inputUser}&config_group=${currentEditGroup}&config_key=${config.key}&new_value=${encodedNewValue}`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            }
                        });
                        
                        const data = await response.json();
                        
                        if (response.ok && data.status === 'success') {
                            // 更新成功，更新原始值
                            const textarea = document.querySelector(`tr[data-key="${config.key}"] textarea`);
                            if (textarea) {
                                textarea.dataset.originalValue = config.newValue;
                            }
                            
                            // 更新主配置数据
                            if (configData[currentEditGroup]) {
                                configData[currentEditGroup][config.key] = config.newValue;
                            }
                            
                            successCount++;
                        } else {
                            failCount++;
                            console.error(`更新配置失败: ${currentEditGroup}.${config.key}`, data.message || '未知错误');
                        }
                    } catch (error) {
                        failCount++;
                        console.error(`更新配置时发生网络错误: ${currentEditGroup}.${config.key}`, error);
                    }
                }
                
                // 显示结果
                if (failCount === 0) {
                    showMessage(`成功更新${successCount}个配置`, 'success');
                    closeGroupConfigModal();
                } else {
                    showMessage(`更新完成: ${successCount}个成功, ${failCount}个失败`, failCount > 0 ? 'error' : 'success');
                }
            } catch (error) {
                showMessage('网络错误：' + error.message, 'error');
            }
        }

        // 弹窗事件监听器
        closeGroupModal.addEventListener('click', closeGroupConfigModal);
        cancelGroupModal.addEventListener('click', closeGroupConfigModal);
        saveGroupModal.addEventListener('click', saveGroupConfig);
        
        // 点击弹窗背景关闭弹窗
        groupConfigModal.addEventListener('click', (event) => {
            if (event.target === groupConfigModal) {
                closeGroupConfigModal();
            }
        });
        
        // 按ESC键关闭弹窗
        document.addEventListener('keydown', (event) => {
            if (event.key === 'Escape' && !groupConfigModal.classList.contains('hidden')) {
                closeGroupConfigModal();
            }
        });

        // 移除原来的操作按钮区域，因为现在不需要批量提交

        // 显示消息函数
        function showMessage(message, type = 'info') {
            // 设置消息类型样式
            resultMessage.className = 'fixed bottom-6 right-6 px-6 py-3 rounded-lg shadow-lg transform translate-y-4 opacity-0 smooth-transition max-w-md';
            if (type === 'success') {
                resultMessage.classList.add('bg-green-100', 'text-green-700', 'border-l-4', 'border-green-500');
            } else if (type === 'error') {
                resultMessage.classList.add('bg-red-100', 'text-red-700', 'border-l-4', 'border-red-500');
            } else {
                resultMessage.classList.add('bg-blue-100', 'text-blue-700', 'border-l-4', 'border-blue-500');
            }

            // 设置消息内容
            resultMessage.textContent = message;

            // 显示消息
            resultMessage.classList.remove('hidden');
            setTimeout(() => {
                resultMessage.classList.remove('translate-y-4', 'opacity-0');
            }, 10);

            // 3秒后隐藏消息
            setTimeout(() => {
                resultMessage.classList.add('translate-y-4', 'opacity-0');
                setTimeout(() => {
                    resultMessage.classList.add('hidden');
                }, 300);
            }, 3000);
        }
    </script>
</body>
</html>